#!/usr/bin/python
# -*-coding:utf-8-*-

from model.dbutils import DBUtils
from utils.model import md5

class User(object):

    def __init__(self, username = None, passwd = None, name = None, 
        birth = None, tel = None, addr = None, postcode = None, 
        uid=None, rdate = None):
        self.username = username 
        self.passwd = passwd
        self.name = name
        self.birth = birth
        self.tel = tel 
        self.addr = addr
        self.postcode = postcode
        self.uid = uid 
        self.rdate = rdate


class UserManager(object):

    def __init__(self):
        self.dbutils = DBUtils()

    def auth(self, user):
        sql = " SELECT passwd FROM user WHERE username = %s "
        rows = self.dbutils.execute_dict(sql, user.username) 
        if rows:  
            passwd = rows[0]['passwd']
            if passwd == md5(user.passwd):
                return True
            else:
                return False
        else:  
            return None 

    def signup(self, user):
        sql = """
            INSERT INTO user(username, passwd, name, birth, 
                tel, addr, postcode)
            VALUES(%s, %s, %s, %s, %s, %s, %s)
            """
        user.passwd = md5(user.passwd)
        params = (user.username, user.passwd, user.name, 
                user.birth, user.tel, user.addr, user.postcode)
        rows = self.dbutils.execute(sql, params)
        if rows is None:
            return False
        else:
            return True

    def check(self, user):
        sql = "SELECT passwd FROM user WHERE username = %s"
        rows = self.dbutils.execute(sql, user.username)
        if rows:
            return True
        else:
            return False

    def query(self, username):
        sql = """
            SELECT id, name, addr, tel, postcode, money
            FROM user WHERE username = %s
        """
        rows = self.dbutils.execute_dict(sql, username)
        if rows:
            user = User()
            data = rows[0]
            user.uid = data['id']
            user.name = data['name'] 
            user.addr = data['addr'] 
            user.tel = data['tel']
            user.postcode = data['postcode']
            user.money = data['money'] 
            user.username = username 
            return user 
        else:
            return None
